package com.dashan.servlets;

import static com.dashan.Constants.SALTED_PWDSHA;
import static com.dashan.Constants.USERNAME;
import static com.dashan.servlets.Parameter.Option.Required;

import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;

import javax.jdo.JDOObjectNotFoundException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.dashan.backend.AuthenticationManager;
import com.dashan.backend.util.XmlHelper;

@SuppressWarnings("serial")
public class GetSessionIdServlet extends DashanServlet {

    @Override
    public ArrayList<Parameter> getParameterList() {
        ArrayList<Parameter> res = super.getParameterList();
        res.add(new Parameter(USERNAME, Required, String.class));
        res.add(new Parameter(SALTED_PWDSHA, Required, String.class));
        return res;
    }

    @Override
    public String getUrlPattern() {
        return "/getsessionid";
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        TreeMap<String, Parameter> params = loadParamters(req);
        
        try {
            long sessionId = AuthenticationManager.getSessionId(
                    params.get(USERNAME).stringValue(), 
                            params.get(SALTED_PWDSHA).stringValue());
            Document xmlDoc = XmlHelper.createXmlDocument("response");
            Element root = xmlDoc.createElement("authentication");
            Element ele = xmlDoc.createElement("sessionid");
            
            ele.appendChild(xmlDoc.createTextNode(sessionId + ""));
            root.appendChild(ele);
            xmlDoc.getDocumentElement().appendChild(root);
            resp.getWriter().print(XmlHelper.xml2String(xmlDoc));
        } catch (JDOObjectNotFoundException e) {
            throw new ServletException("User not found: " + e.getMessage());
        } catch (SecurityException e) {
            throw new ServletException("Wrong salted password!");
        }
    }
}
